/*
 * @Description: 标准性检测上下文
 * @Author: Rfan
 * @Date: 2022-10-09 11:36:40
 * @LastEditTime: 2022-10-20 15:23:50
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { message, Modal } from 'antd';
import { ArchivesDetectionReducer } from '../reducers/ArchivesDetectionReducer';
import {
  ADD_DETECTION_PLAN,
  DELETE_DETECTION_PLAN,
  EDIT_DETECTION_PLAN,
  GET_DETECTION_PLAN_LIST,
  SET_LEVEL_LIST,
  SET_SELECT_AT,
  SET_SELECT_FOND
} from '../constants';
import { fetchLevelByATId } from '@/api/archivesType';
import { checkedObjTypeList } from '../dictionaries';
import {
  addDetectionPlan,
  deleteDetectionPlan,
  editDetectionPlan,
  fetchDetectionListByPage
} from '@/api/standardizedDetection/detectionPlan';
import { SET_SELECTED_ITEM } from '@/view/accession/BatchManage/constants';
import { selectItemByKey } from '@/utils/list';

const initialState = {
  // 当前选中的项目
  selectFond: {},
  selectAT: {},

  // 方案列表
  list: [],
  // 当前档案类型层级列表
  levelList: [],
  levelListWithoutERecord: [],

  initRule: {},
  // 选中的表格条目
  selectItems: [],

  // -------- 字典 --------
  // 检测对象类型
  checkedObjTypeList
};

const ArchivesDetectionContext = createContext();

const ArchivesDetectionContextProvider = (props) => {
  const [state, dispatch] = useReducer(ArchivesDetectionReducer, initialState);

  const actions = {
    /**
     * @description: 设置选中的全宗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 获取分组字段列表
     */
    getLevelList() {
      fetchLevelByATId(state.selectAT.id).then((res) => {
        const { data } = res;
        data && dispatch({ type: SET_LEVEL_LIST, data });
      });
    },

    /**
     * @description: 获取检测方案列表
     * @param {*} query
     */
    getPlanList(query) {
      return new Promise((resolve, reject) => {
        fetchDetectionListByPage(query)
          .then((res) => {
            const { data } = res;
            dispatch({ type: GET_DETECTION_PLAN_LIST, data: data.results || [] });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 添加检测方案
     * @param {*} query
     */
    addDetectionPlanFunc(query) {
      return new Promise((resolve, reject) => {
        addDetectionPlan(query)
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_DETECTION_PLAN, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 编辑检测方案
     * @param {*} query
     */
    editDetectionPlanFunc(query) {
      return new Promise((resolve, reject) => {
        editDetectionPlan(query)
          .then((res) => {
            const { data } = res;
            dispatch({ type: EDIT_DETECTION_PLAN, data, id: data.id });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 删除检测方案
     */
    delDetectionPlanFunc(id, title = '确认删除此方案？') {
      Modal.confirm({
        title: '删除',
        content: title,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteDetectionPlan(ids).then((res) => {
            message.success('删除成功');
            const data = res.data.map((item) => parseInt(item, 10));
            dispatch({ type: DELETE_DETECTION_PLAN, ids: data });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    }
  };

  const filters = {
    getCheckObjName(id) {
      return selectItemByKey(id, state.checkedObjTypeList)?.name || '-';
    }
  };

  // watch选中的单位来加载全宗
  useEffect(() => {
    if (JSON.stringify(state.selectAT) !== '{}') {
      actions.getLevelList();
    }
  }, [state.selectAT]);

  return (
    <ArchivesDetectionContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </ArchivesDetectionContext.Provider>
  );
};

export const useArchivesDetectionContext = () => {
  return useContext(ArchivesDetectionContext);
};

export { ArchivesDetectionContext, ArchivesDetectionContextProvider };
